package cn.wolfcode.rbac.controller;

import cn.wolfcode.rbac.domain.Department;
import cn.wolfcode.rbac.domain.Role;
import cn.wolfcode.rbac.query.PageResult;
import cn.wolfcode.rbac.query.QueryObject;
import cn.wolfcode.rbac.service.IDepartmentService;
import cn.wolfcode.rbac.service.IEmployeeService;
import cn.wolfcode.rbac.service.IPermissionService;
import cn.wolfcode.rbac.service.IRoleService;
import cn.wolfcode.rbac.util.RequiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;
    @Autowired
    private IPermissionService permissionService;

    @RequestMapping("/list")
    @RequiredPermission({"角色列表","role:list"})
    public String listAll(Model model, QueryObject qo){
        PageResult pageResult = roleService.query(qo);
        model.addAttribute("pageResult",pageResult);
        List<Role> roles = roleService.listAll();
        model.addAttribute("departments",roles);
        //把载具里面的数据传递给用户看
        //请求转发
        //return "forward:/WEB-INF/views/role/list.jsp";
        return "role/list";
    }

    @RequestMapping("/delete")
    @RequiredPermission({"角色删除","role:delete"})
    public String delete(Long id){
        roleService.delete(id);
        //重定向,重新定位到一个新的请求路径
        return "redirect:/role/list";
    }


    //跳转到input页面
    @RequestMapping("/input")
    public String input(Model model,Long id){
        if (id != null) {
            Role one = roleService.getOne(id);
            model.addAttribute("role",one);
        }

        // 把系统中所有的权限的信息放到作用域中
        model.addAttribute("permissions",permissionService.listAll());
        
        //请求转发
        return "role/input";
    }


    //跳转到input页面之后,填完/修改完数据信息之后,点击保存按钮
    //把数据保存到数据库,然后重定向到 role/list 请求路径,相当于又帮我们查了一次
    @RequestMapping("/saveOrUpdate")
    @RequiredPermission({"角色新增修改","role:saveOrUpdate"})
    public String saveOrUpdate(Role role,Long[] permissionIds){
        roleService.saveOrUpdate(role,permissionIds);
        //保存/修改之后, 重定向到role/list请求路径,相当于重新查询了一次最新的数据
        return "redirect:/role/list";
    }
}
